package com.itmake.sample.ali.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * oos 接口的封装类
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Component
public class AliOssClient {

    @Autowired
    private AliOssConfig aliOssConfig;

    /**
     * 上传文件
     * @param fileName 文件名称
     * @param inputStream 输入流
     * @return PutObjectResult
     */
    public PutObjectResult upload(String fileName, InputStream inputStream) {
        OSS ossClient = getOssClient();
        // 上传文件流
        PutObjectResult putObjectResult = ossClient.putObject(aliOssConfig.bucket, fileName, inputStream);
        // 关闭OSSClient。
        closeOssClient(ossClient);
        return putObjectResult;
    }

    /**
     * 删除文件
     * @param path 文件路径
     */
    public void delete(String path) {
        OSS ossClient = getOssClient();
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(aliOssConfig.bucket, path);
        // 关闭OSSClient。
        closeOssClient(ossClient);
    }

    /**
     * 获取 oss 实例
     * @return oss 实例
     */
    private OSS getOssClient() {
        return new OSSClientBuilder().build(
                aliOssConfig.endpoint,
                aliOssConfig.accessKeyId,
                aliOssConfig.accessKeySecret
        );
    }

    /**
     * 关闭 oss 实例
     * @param ossClient oss 实例
     */
    private void closeOssClient(OSS ossClient) {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}
